package ru.bytedog.oiot.counter.bot.exception;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import ru.bytedog.oiot.counter.bot.bean.ErrorCode;

/**
 * Общая ошибка сервиса
 */
public class ServiceException extends Exception {

    private final ErrorCode errorInfo;
    private final String additionalMessage;
    private final Object[] args;

    public ServiceException(ErrorCode errorInfo) {
        this(errorInfo, null, null);
    }

    public ServiceException(ErrorCode errorInfo, Object... args) {
        this(errorInfo, null, args);
    }

    public ServiceException(ErrorCode errorInfo, String additionalMessage, Object[] args) {
        super(getErrorMessage(errorInfo, additionalMessage, args));
        this.errorInfo = errorInfo;
        this.additionalMessage = additionalMessage;
        this.args = args;
    }

    private static String getErrorMessage(ErrorCode errorInfo, String additionalMessage, Object[] args) {
        StringBuilder message = new StringBuilder();
        message.append(ArrayUtils.isNotEmpty(args) ? String.format(errorInfo.getMessageTemplate(), args) : errorInfo.getMessageTemplate());
        if (StringUtils.isNotBlank(additionalMessage)) {
            message.append(". ").append(additionalMessage);
        }
        return message.toString();
    }

    public ErrorCode getErrorInfo() {
        return errorInfo;
    }

    public String getAdditionalMessage() {
        return additionalMessage;
    }

    public Object[] getArgs() {
        return args;
    }
}
